<template>
  <div class="app-container">
    <div class="app-container-inner">
      <!-- 搜索条件 -->
      <div class="search">
        <div style="display: flex; gap: 5px">
          <HPlainButton @click="onSync">同步模版</HPlainButton>
          <!--批量操作-->
          <el-dropdown trigger="click">
            <HButton :disabled="ids.length == 0">
              批量操作
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleChangeAll(false, '启用')">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量启用
                </el-dropdown-item>
                <el-dropdown-item @click="handleChangeAll(true, '禁用')">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  批量禁用
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div style="display: flex; gap: 5px">
          <!-- 模版名称/模版内容 -->

          <!-- 模版类型 -->
          <el-select
            v-model="filter.type"
            placeholder="请选择"
            clearable
            style="width: 100px; height: 28px"
            @change="getSmsTemplateList"
          >
            <el-option
              v-for="item in typeOptional"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="filter.keyword"
            clearable
            style="width: 140px"
            placeholder="模版名称/模版内容"
            @clear="getSmsTemplateList"
            @keyup.enter="getSmsTemplateList"
          />
          <HButton type="primary" @click="getSmsTemplateList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
          <HButton @click="onReset">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <div
        v-loading="getSmsTemplateListLoading || syncSmsTemplateLoading || updateSmsTemplateLoading"
        class="table"
      >
        <el-table
          :data="smsTemplateList"
          border
          resizable
          stripe
          style="position: absolute"
          @selection-change="handleSelectionChange"
          height="100%"
        >
          <!--选择-->
          <el-table-column type="selection" width="40" fixed />

          <!-- 序号 -->
          <el-table-column label="序号" type="index" width="50" />

          <!-- 模版名称 -->
          <el-table-column label="模版名称" prop="name" show-overflow-tooltip width="160" />

          <!-- 模版类型 -->
          <el-table-column label="模版类型" prop="type" show-overflow-tooltip width="86">
            <template #default="scope">
              <span v-if="scope.row.type === 1">验证类短信</span>
              <span v-else-if="scope.row.type === 2">通知类</span>
              <span v-else>推广类</span>
            </template>
          </el-table-column>

          <!-- 模版编号 -->
          <el-table-column label="模版编号" prop="code" show-overflow-tooltip width="110" />

          <!-- 模版内容 -->
          <el-table-column label="模版内容" min-width="150" prop="content" show-overflow-tooltip />

          <!-- 发布状态 -->
          <el-table-column label="发布状态" prop="release" show-overflow-tooltip width="84">
            <template #default="scope">
              <HStatus v-if="scope.row.release">已发布</HStatus>
              <HStatus v-else type="info">已下架</HStatus>
            </template>
          </el-table-column>

          <!-- 是否发布 -->
          <el-table-column label="是否启用" prop="status" show-overflow-tooltip width="80">
            <template #default="scope">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-else type="info">禁用</HStatus>
            </template>
          </el-table-column>
          <!-- 接受者类型 -->
          <el-table-column label="接受者类型" prop="roleTypeStr" show-overflow-tooltip width="90">
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip width="128" />

          <!-- 更新时间 -->
          <el-table-column label="更新时间" prop="updateTime" show-overflow-tooltip width="128" />

          <!-- 操作 -->
          <el-table-column fixed="right" label="操作" show-overflow-tooltip width="170">
            <template #default="scope">
              <el-space :size="0" :spacer="spacer">
                <HLink @click="receiverRole(scope.row.id)" v-if="scope.row.updateReceiveRole"
                  >修改接收人</HLink
                >
                <SmsTemplateDetail :sms-template-id="scope.row.id" @update="getSmsTemplateList">
                  <HLink>详细</HLink>
                </SmsTemplateDetail>
                <HLink v-if="scope.row.status" @click="handleChange(scope.row.id, false, '启用')"
                  >启用</HLink
                >
                <HLink v-else @click="handleChange(scope.row.id, true, '禁用')">禁用</HLink>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer">
        <!-- 分页 -->
        <div class="pagina">
          <Pagination
            ref="paginationRef"
            :list_total="Number(totalList)"
            @size-change="getSmsTemplateList"
            @current-change="getSmsTemplateList"
          />
        </div>
      </div>
    </div>

    <!--接收者 -->
    <HModal v-model="dialogVisible" title="接收者角色" :width="550">
      <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm">
        <el-form-item label="接收者类型" prop="roleTypes" style="margin-bottom: 18px">
          <el-select multiple v-model="ruleForm.roleTypes" class="factory_product">
            <el-option v-for="emp in listType" :key="emp.id" :value="emp.id" :label="emp.name" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="指定人员"
          prop="empIds"
          style="margin-bottom: 18px"
          v-if="ruleForm.roleTypes.includes('2')"
        >
          <el-select
            multiple
            class="factory_product"
            v-model="ruleForm.empIds"
            :disabled="!ruleForm.roleTypes.includes('2')"
          >
            <el-option v-for="emp in empOptional" :key="emp.id" :value="emp.id" :label="emp.name" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton type="primary" is-modal @click="Confirm(ruleFormRef)">确定</HButton>
        <HButton is-modal @click=";(dialogVisible = false), ruleFormRef.resetFields()">
          取消
        </HButton>
      </template>
    </HModal>
  </div>
</template>

<script lang="ts" setup>
  import Pagination from '@/components/Pagination/index.vue'
  import { onMounted, ref, h, watch } from 'vue'
  import { ArrowDown, CircleCheck, RefreshRight, Search, Warning } from '@element-plus/icons-vue'
  import smsListService from './services/list'
  import smsDetailService from './services/detail'
  import SmsTemplateDetail from './components/SmsTemplateDetail.vue'
  import { ElDivider, ElMessage, ElMessageBox } from 'element-plus'
  import { SmsTemplateListItem } from './types'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import { getRoleType, getTemplateRoleType, saveRoleType } from '@/api/sms'
  import { empPageSelecct } from '@/api/organize'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.note.noteTemplateList,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const {
    totalList,
    smsTemplateList,
    syncSmsTemplateLoading,
    getSmsTemplateListLoading,
    getSmsTemplatesFn,
    syncSmsTemplateFn,
  } = smsListService

  // 分页组件实例
  const paginationRef = ref<InstanceType<typeof Pagination> | null>(null)

  // 筛选条件
  const filter = ref({
    keyword: '',
    type: null,
  })

  // 类型选择
  const typeOptional = [
    { value: '1', label: '验证类短信' },
    { value: '2', label: '通知类' },
    { value: '3', label: '推广类短信' },
  ]

  // 获取短信模版列表
  const getSmsTemplateList = () => {
    const __filter = getFilter()
    getSmsTemplatesFn(__filter)
  }

  // 重置事件
  const onReset = () => {
    Object.assign(filter.value, {
      keyword: '',
      type: null,
    })
    getSmsTemplateList()
  }

  // 处理filter搜索条件
  const getFilter = () => {
    const result = {
      page: 1,
      limit: 50,
      keyword: '',
      type: null,
    }

    result.keyword = filter.value.keyword
    result.type = filter.value.type

    if (paginationRef.value) {
      result.page = paginationRef.value.current
      result.limit = paginationRef.value.size
    }

    return result
  }

  // 同步事件
  const onSync = async () => {
    const res = await syncSmsTemplateFn()
    getSmsTemplateList()
    ElMessage({
      type: res.code === 20000 ? 'success' : 'error',
      message: res.message,
    })
  }
  /****
   * 接受者
   *
   */
  const dialogVisible = ref(false)
  const ruleForm = ref({
    empIds: [], //人员ID，当roleType=2时，此字段必填
    roleTypes: [], //短信接收者角色类型ID
  })
  // 验证规则
  const rules = ref({
    empIds: [{ required: true, message: '请选择人员', trigger: 'change' }],
    roleTypes: [{ required: true, message: '接受者类型', trigger: 'change' }],
  })
  const ruleFormRef = ref()
  const listType = ref([])
  const empId = ref('')
  const receiverRole = (id) => {
    empId.value = id
    Promise.all([getRoleType(id), getTemplateRoleType(id)]).then(([res, res2]) => {
      //选择角色列表
      if (!res.data.success) {
        if (res.data.isError)
          ElMessage({
            type: 'error',
            message: res.data.message,
          })
      } else {
        listType.value = res.data.data.rows
      }
      // 详情
      if (!res2.data.success) {
        ElMessage({
          type: 'error',
          message: res2.data.message,
        })
      } else {
        ruleForm.value.empIds = res2.data.data.rows.empIds || []
        ruleForm.value.roleTypes = res2.data.data.rows.roleTypes || []
        ruleForm.value.roleTypes = ruleForm.value.roleTypes.map((o) => o.toString())
      }
      dialogVisible.value = true
    })
  }
  const Confirm = (el) => {
    if (!el) return
    el.validate((vali) => {
      if (vali) {
        saveRoleType(ruleForm.value, empId.value).then((res) => {
          if (res.data.isError)
            ElMessage({
              type: res.data.success ? 'success' : 'error',
              message: res.data.message,
            })
          if (res.data.success) {
            getSmsTemplateList()
            dialogVisible.value = false
          }
        })
      }
    })
  }

  watch(
    () => ruleForm.value.roleTypes,
    (n) => {
      if (n.includes('2')) {
        getEmpOptional()
      } else {
        ruleForm.value.empIds = []
      }
    },
  )
  // 指定人员下拉选项
  const empOptional = ref([])

  // 获取指定人员下拉选项加载
  const getEmpOptionalLoading = ref(false)

  // 获取指定人员下拉选项
  const getEmpOptional = async () => {
    getEmpOptionalLoading.value = true
    const res = await empPageSelecct({ limit: 0, name: '', page: 0 })
    getEmpOptionalLoading.value = false
    empOptional.value = res.data.data.rows
  }

  // 选中的列
  const ids = ref<Array<number | string>>([])

  // 表格多选事件
  const handleSelectionChange = (smsTemplateList: Array<SmsTemplateListItem>) => {
    ids.value = []
    smsTemplateList.filter((o) => {
      ids.value.push(o.id)
    })
  }

  const { updateSmsTemplateFn, updateSmsTemplateLoading } = smsDetailService

  // 批量修改状态事件
  const handleChangeAll = (status: boolean, str: string) => {
    if (ids.value.length == 0) {
      ElMessage({
        message: `请选择要${str}的短信模版`,
        type: 'warning',
        duration: 2000,
        offset: 200,
      })
      return
    }
    ElMessageBox({
      //
      title: '提示',
      message: `确认${str}的该短信模版?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    }).then(async () => {
      const res = await updateSmsTemplateFn(ids.value, status)
      getSmsTemplateList()
      ElMessage({
        type: res.code === 20000 ? 'success' : 'error',
        message: res.message,
      })
    })
  }

  // 修改单个状态事件
  const handleChange = (id: string | number, status: boolean, str: string) => {
    ElMessageBox({
      //
      title: '提示',
      message: `确认${str}的该短信模版?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
    }).then(async () => {
      const res = await updateSmsTemplateFn([id], status)
      getSmsTemplateList()
      ElMessage({
        type: res.code === 20000 ? 'success' : 'error',
        message: res.message,
      })
    })
  }

  onMounted(() => {
    getSmsTemplateList()
  })
</script>

<style lang="scss" scoped>
  @import './index';
</style>
